package com.wanban.download.utils

import android.util.Log
import io.reactivex.Flowable
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import java.util.concurrent.TimeUnit
import kotlin.Long
import kotlin.NullPointerException
import kotlin.Unit


object RxJavaUtils {

    fun <T> doAsync(exec: () -> T?, success: (t: T) -> Unit, fail: () -> Unit): Disposable {
        return Observable.create {
            val result = exec()
            if (result == null) {
                it.onError(NullPointerException())
            } else {
                it.onNext(result)
            }
        }.subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({
                success(it)
            }, {
                fail()
            }, {
                Log.e("RxJavaUtils", "doAsync 执行完成....")
            })
    }

    fun delay(
        delay: Long,
        success: (Long) -> Unit
    ): Disposable {
        return Flowable.timer(delay, TimeUnit.MILLISECONDS)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({
                success(it)
            }, {
                it?.printStackTrace()
            })
    }
    fun <T> doAsync(exec: () -> T?, success: (t: T) -> Unit): Disposable {
        return doAsync(exec, success) {}
    }

    fun <T> doAsync(exec: () -> T?): Disposable {
        return doAsync(exec, {}) {}
    }
}